package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.PAnswer;
import com.ruoyi.system.domain.PQuestion;
import com.ruoyi.system.domain.PResume;
import com.ruoyi.system.domain.bo.PAnswerBo;
import com.ruoyi.system.domain.vo.PAnswerVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IPAnswerService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 问题答案Service业务层处理
 *
 * @author ruoyi
 * @date 2022-07-19
 */
@RequiredArgsConstructor
@Service
public class PAnswerServiceImpl implements IPAnswerService {

    private final PAnswerMapper baseMapper;
    private final PQuestionMapper pQuestionMapper;
    private final SysUserMapper sysUserMapper;
    private final SysDictDataMapper sysDictDataMapper;
    private final PResumeMapper pResumeMapper;

    /**
     * 查询问题答案
     */
    @Override
    public PAnswer queryById(Long id){
        return baseMapper.selectMyInfo(id);
    }

    /**
     * 查询问题答案列表
     */
    @Override
    public TableDataInfo<PAnswer> queryPageList(PAnswer bo, PageQuery pageQuery) {
        QueryWrapper<PAnswer> lqw = Wrappers.query();
        lqw.eq(ObjectUtil.isNotNull(bo.getTypeId()), "a.type_id", bo.getTypeId())
            .eq(StringUtils.isNotBlank(bo.getTitle()), "q.title", bo.getTitle());
        Page<PAnswer> result = baseMapper.selectMyPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询问题答案列表
     */
    @Override
    public List<PAnswerVo> queryList(PAnswerBo bo) {
        LambdaQueryWrapper<PAnswer> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PAnswer> buildQueryWrapper(PAnswerBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PAnswer> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getQId() != null, PAnswer::getQId, bo.getQId());
        lqw.eq(bo.getReplyUserId() != null, PAnswer::getReplyUserId, bo.getReplyUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getReplyTitle()), PAnswer::getReplyTitle, bo.getReplyTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getReplyMsg()), PAnswer::getReplyMsg, bo.getReplyMsg());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), PAnswer::getType, bo.getType());
        lqw.eq(bo.getTypeId() != null, PAnswer::getTypeId, bo.getTypeId());
        return lqw;
    }

    /**
     * 新增问题答案
     */
    @Override
    public Boolean insertByBo(PAnswerBo bo) {
        PAnswer add = BeanUtil.toBean(bo, PAnswer.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改问题答案
     */
    @Override
    public Boolean updateByBo(PAnswerBo bo) {
        PAnswer update = BeanUtil.toBean(bo, PAnswer.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PAnswer entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除问题答案
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<PAnswer> queryListByQid(Long id) {
        return baseMapper.selectListByQid(id);
    }

    @Override
    public PAnswer addAnswer(PAnswer answer) {
        PAnswer pa = new PAnswer();
        pa.setQId(answer.getQId())
            .setReplyMsg(answer.getReplyMsg())
            .setReplyUserId(LoginHelper.getUserId());
        this.baseMapper.insert(pa);
        SysUser user = this.sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, LoginHelper.getUserId()));
        pa.setUserName(user.getUserName())
            .setAvatar(user.getWxAvatar())
            .setLevelInfo(this.sysDictDataMapper.selectOne(new LambdaQueryWrapper<SysDictData>().select(SysDictData::getDictLabel)
                .eq(SysDictData::getDictType, "advisor_type").eq(SysDictData::getDictValue, this.pResumeMapper.selectOne(new LambdaQueryWrapper<PResume>()
                    .select(PResume::getLevelInfo).eq(PResume::getUserId, user.getUserId())).getLevelInfo())).getDictLabel());
        return pa;
    }

    @Override
    public TableDataInfo<PAnswer> detailAnswer(Long questionId, PageQuery pageQuery) {
        pageQuery.setPageNum((pageQuery.getPageNum() - 1) * pageQuery.getPageSize());
        return TableDataInfo.build(this.baseMapper.selectListByQuestionId(pageQuery, questionId));
    }

    @Override
    public void addQuestion(PQuestion pQuestion) {
        PQuestion pq = new PQuestion();
        pq.setTitle(pQuestion.getTitle())
            .setMsg(pQuestion.getMsg())
            .setTypeId(pQuestion.getTypeId())
            .setTagType(pQuestion.getTagType())
            .setIsAnonymous(pQuestion.getIsAnonymous())
            .setExpertsVisible(pQuestion.getExpertsVisible())
            .setUserId(LoginHelper.getUserId());
        if (this.pQuestionMapper.insert(pq) != 1) {
            throw new ServiceException("发布失败！");
        }
    }
}
